package org.stormphoenix.bbsfamily.controller


import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiParam
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.*
import org.stormphoenix.bbsfamily.config.UserService
import org.stormphoenix.bbsfamily.entity.dto.UserDTO
import javax.servlet.http.HttpServletResponse
import javax.validation.Valid

@RestController
@Validated
@Api(value = "IndexController Api 接口文档")
class IndexController : BaseController() {
    @Value("\${bbs.name}")
    lateinit var name: String

    @Autowired
    @Qualifier("userService")
    lateinit var userService: UserService

    @RequestMapping("/")
    fun index(): Any = returnSuccess(DescEnum.SUCCESS)

    @ApiOperation(value = "用户登录", produces = "application/json")
    @PostMapping("/signin")
    fun signin(
        @ApiParam(name = "username", value = "用户名", required = true)
        @RequestParam(value = "username", required = true)
        username: String,

        @ApiParam(name = "password", value = "密码", required = true)
        @RequestParam(value = "password", required = true)
        password: String,

        response: HttpServletResponse
    ): CommonResult<Any> {
        var token = userService.login(username, password)
        return if (token != null) {
            response.addHeader("Authorization", "Bearer $token")
            returnSuccess(DescEnum.SIGN_IN_SUCCESS, data = "Bearer $token")
        } else {
            returnError(DescEnum.SIGN_IN_USERNAME_OR_PASSWORD_ERROR)
        }
    }

    @ApiOperation(value = "用户注册", produces = "application/json")
    @PostMapping("/signup", consumes = ["application/json"])
    fun signup(@Valid @RequestBody body: UserDTO): CommonResult<Any> {
        val result = userService.register(body)
        return when (result) {
            UserService.REGISTER_SUCCESS -> returnSuccess(DescEnum.SIGN_UP_SUCCESS)
            UserService.USER_EXIST -> returnError(DescEnum.SIGN_UP_USER_EXIST, "${body.username} already exist. ")
            else -> returnError(desc = DescEnum.UNKNOWN_REASON)
        }
    }
}